
const fs = require('fs-extra')
const shell = require('shelljs')
const ora = require('ora')
const { load } = require('cheerio')
let loading = ora()

const _appRootPath = '/Users/caoyq/Work/微盟/MWMainAPP/XYMainApp'
const _archivePath = '/Users/caoyq/Work/微盟/MWMainAPP/XYMainApp/archive_result/20201124.xcarchive'
const _buildDir = '/Users/caoyq/Work/微盟/MWMainAPP/XYMainApp/build_result/'
const _logPath = '/Users/caoyq/Work/微盟/MWMainAPP/XYMainApp/package.log'

module.exports = async function() {
    console.log('start')
    // 1.进入项目路径
    shell.cd(_appRootPath)

    try {
        buildCommand()
        // await cleanCommand()
        // await archiveCommand()
        console.log('end')
    } catch (error) {
        console.log(error)
        shell.exit(1)
    }
}

/*
 * 执行 clean 命令
 */
function cleanCommand() {
    return new Promise((resolve, reject) => {
        loading.start('cleaning...')
        let clean_startTime = new Date().getTime()
        let clean_cmd = 'xcodebuild clean -workspace XYMainApp.xcworkspace\
                                          -scheme XYMainApp -configuration Debug -sdk iphonesimulator'
        shell.exec(clean_cmd, {silent: true}, function(code, stdout, stderr){
            saveLog(stdout)
            loading.stop()
            if (code != 0) {
                reject(stderr)
                return
            }
            let clean_endTime = new Date().getTime()
            console.log(`** CLEAN SUCCEEDED ** [${(clean_endTime - clean_startTime)/1000} sec]`)
            resolve() 
        })
    })
}

/*
 * 执行 archive 命令
 */
function archiveCommand() {
    return new Promise((resolve, reject) => {
        loading.start('archiving...')
        let archive_startTime = new Date().getTime()
        let archive_cmd = `xcodebuild archive -workspace XYMainApp.xcworkspace\
                                      -scheme XYMainApp -configuration Debug -archivePath ${_archivePath}`
        shell.exec(archive_cmd, {silent:true}, function(code, stdout, stderr){
            saveLog(stdout)
            loading.stop()
            if (code != 0) {
                reject(stderr)
                return
            }
            let archive_endTime = new Date().getTime()
            console.log(`** ARCHIVE SUCCEEDED ** [${(archive_startTime - archive_endTime)/1000} sec]`)
            resolve() 
        })
    })
}

function buildCommand() {
    let build_cmd = `xcodebuild build -workspace XYMainApp.xcworkspace\ 
                                      -scheme XYMainApp ONLY_ACTIVE_ARCH=NO -configuration Debug -sdk iphonesimulator`
    shell.exec(build_cmd)
}

function saveLog(stdout) {
    fs.appendFileSync(_logPath, `\n${Date()}\n${stdout}\n`)
}